/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.menuItem;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.MenuItem;
import com.blandware.atleap.service.core.MenuManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.MenuItemForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Changes menu item position on specified layer
 * </p>
 * <p><a href="MoveMenuItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.22 $ $Date: 2008/04/29 17:48:09 $
 * @struts.action path="/core/menuItem/move"
 * name="menuItemForm"
 * validate="false"
 * roles="core-menuItem-move"
 * @struts.action-forward name="listMenuItems"
 * path="/core/menuItem/list.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/menuItem/list.do"
 */
public final class MoveMenuItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		MenuItemForm menuItemForm = (MenuItemForm) form;
		Long ownerId = null;
		if ( !GenericValidator.isBlankOrNull(menuItemForm.getOwnerId()) ) {
			ownerId = Long.valueOf(menuItemForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		Long menuItemId = null;
		if ( !GenericValidator.isBlankOrNull(menuItemForm.getId()) ) {
			menuItemId = Long.valueOf(menuItemForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing menu item ID. Returning to list");
			}
			return mapping.findForward("listMenuItems");
		}

		Integer position = null;
		if ( !GenericValidator.isBlankOrNull(request.getParameter("position")) ) {
			position = Integer.valueOf(request.getParameter("position"));
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Position is not specified. Returning to list...");
			}
			return mapping.findForward("listMenuItems");
		}

		Integer index = null;
		if ( !GenericValidator.isBlankOrNull(request.getParameter("position")) ) {
			index = Integer.valueOf(request.getParameter("index"));
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Index is not specified. Returning to list...");
			}
			return mapping.findForward("listMenuItems");
		}

		MenuManager menuManager = (MenuManager) getBean(Constants.MENU_MANAGER_BEAN);

		// lookup for item with specified ID
		MenuItem menuItem = menuManager.retrieveMenuItem(menuItemId);

		if ( menuItem == null ) {
			// menuItem not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("menuItemNotFound", new ActionMessage("core.menuItem.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listMenuItems");
		}

		Long parentItemId = null;
		if ( menuItem.getParentItem() != null ) {
			parentItemId = menuItem.getParentItem().getId();
		}

		// lookup for redefinition on current layer
		MenuItem redefinitionItem = null;
		if ( menuItem.getOwner() != null && menuItem.getOwner().getId().equals(ownerId) ) {
			// if this item was created on this layer, there is no need to create its redefinition
			redefinitionItem = menuItem;
		} else {
			redefinitionItem = menuManager.findRedefinitionItem(menuItem.getId(), ownerId);
		}

		// lookup item on position where to move
		MenuItem existingItem = menuManager.findMenuItemByPositionAndParentAndOwner(position, parentItemId, ownerId);
		if ( existingItem != null ) {
			// move existing item temporarily to the end of list
			existingItem.setPosition(null);
			try {
				menuManager.updateMenuItem(existingItem, parentItemId, ownerId);
			} catch ( ObjectOptimisticLockingFailureException e ) {
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.menuItem.errors.updateFailed"));
				saveErrors(request, errors);
				return mapping.findForward("listMenuItems");
			}
		}

		if ( redefinitionItem == null ) {
			// redefinition does not exist, we must create it
			redefinitionItem = new MenuItem();
			redefinitionItem.setIdentifier(null);
			redefinitionItem.setPosition(position);
			redefinitionItem.setVisibility(menuItem.getVisibility());
			redefinitionItem.setOrigItem(menuItem);
			menuManager.createMenuItem(redefinitionItem, parentItemId, ownerId);
		} else {
			// redefinition already exists, move it to position
			redefinitionItem.setPosition(position);
			try {
				menuManager.updateMenuItem(redefinitionItem, parentItemId, ownerId);
			} catch ( ObjectOptimisticLockingFailureException e ) {
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.menuItem.errors.updateFailed"));
				saveErrors(request, errors);
				return mapping.findForward("listMenuItems");
			}
		}

		if ( existingItem != null ) {
			// move existing item to index
			existingItem.setPosition(index);
			try {
				menuManager.updateMenuItem(existingItem, parentItemId, ownerId);
			} catch ( ObjectOptimisticLockingFailureException e ) {
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.menuItem.errors.updateFailed"));
				saveErrors(request, errors);
				return mapping.findForward("listMenuItems");
			}
		}

		// flush cache
		CacheUtil cacheUtil = CacheUtil.getInstance(request);
		cacheUtil.flushMenuCache();
		cacheUtil.flushContentPageCache();

		return mapping.findForward("listMenuItems");
	}


}